package com.hzsd.zengbanyi.biaodan_text.Actrivity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.TextView;
import android.widget.Toast;

import com.hzsd.zengbanyi.biaodan_text.BaseActivity;
import com.hzsd.zengbanyi.biaodan_text.R;
import com.hzsd.zengbanyi.biaodan_text.bean.WorkDAO;
import com.hzsd.zengbanyi.biaodan_text.service.UploadLogService;
import com.hzsd.zengbanyi.biaodan_text.utils.FileUtil;
import com.hzsd.zengbanyi.biaodan_text.weight.Bimp;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

public class MedioActivity extends BaseActivity implements OnClickListener, OnItemLongClickListener, OnItemClickListener {
	private GridView gridView;
	private ArrayList<String> list;
	private TextView tvChoosePic,tvSave,tvChangeMV,tvPhoto;
	private RelativeLayout rlReturn;
	private String absolutePath;
	private String filename,taskSceneId;
	private TextView resulView;
	private SimpleAdapter adapter;
	private ArrayList<HashMap<String, Object>> data;
//	private ProgressBar uploadbar;
	private UploadLogService logService;
	private ProgressDialog selectorDialog;
	private File uploadFile;
	private WorkDAO workdao;
	private boolean start = true;	
	
	private String fileName;
	private Bitmap photo = null;
	String saveDir = Environment.getExternalStorageDirectory()  
            + "/hjjc/imgs/";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_medio);
		initView();
		init();
	}


	private void init() {
		workdao=new WorkDAO(MedioActivity.this);
		
		list=workdao.GetPicPath(taskSceneId);
		 data = new ArrayList<HashMap<String, Object>>();
		if (list!=null) {
			Bimp.bmp=new ArrayList<Bitmap>();
						 
			ArrayList<String> names = new ArrayList<String>();
			for (int i = 0; i < list.size(); i++) {
				String name=getName(list.get(i));
				names.add(name);
				
					
					try {
						Bitmap bm=Bimp.revitionImageSize(list.get(i));
						Bimp.bmp.add(bm);
					} catch (IOException e) {
						e.printStackTrace();
					}
				
				
			}
			for (int i = 0; i <list.size(); i++) {
				HashMap<String,Object> map = new HashMap<String, Object>();
				map.put("path", names.get(i));
				map.put("pic", Bimp.bmp.get(i));
				data.add(map);
			}
			 adapter = new SimpleAdapter(MedioActivity.this,data,R.layout.simple_list_item,new String[]{"pic","path"},new int[]{R.id.iv,R.id.tv});
			adapter.setViewBinder(new ViewBinder() {			
				@Override
				public boolean setViewValue(View view, Object object,
						String textRepresentation) {
					 //判断是否为我们要处理的对象  
	                if(view instanceof ImageView  && object instanceof Bitmap){  
	                    ImageView iv = (ImageView) view;         
	                    iv.setImageBitmap((Bitmap) object);  
	                    return true;  
	                }else  
	                return false;  
				}
			});
			gridView.setAdapter(adapter);
		}

	    }	
//	
		

		public String getName(String pathandname){  
	        
	        int start=pathandname.lastIndexOf("/");  
	        int end=pathandname.lastIndexOf(".");  
	        if(start!=-1 && end!=-1){  
	            return pathandname.substring(start+1,end);    
	        }else{  
	            return null;  
	        }    
	    }
	private void initView() {
		// TODO Auto-generated method stub
		rlReturn=(RelativeLayout)findViewById(R.id.rl_return);
		gridView=(GridView)findViewById(R.id.gridview);
		tvChoosePic=(TextView)findViewById(R.id.tv_choose_pic);
		tvSave=(TextView)findViewById(R.id.tv_save);
		tvChangeMV=(TextView)findViewById(R.id.tv_duomeiti);
		tvPhoto=(TextView)findViewById(R.id.tv_photo);
		logService= new UploadLogService(MedioActivity.this);
		
		
		tvPhoto.setOnClickListener(this);
		tvSave.setOnClickListener(this);
		tvChoosePic.setOnClickListener(this);
		tvChangeMV.setOnClickListener(this);
		rlReturn.setOnClickListener(this);
		gridView.setOnItemLongClickListener(this);
		gridView.setOnItemClickListener(this);
		
		SharedPreferences share = getSharedPreferences("user", MODE_PRIVATE);   
		taskSceneId=share.getString("taskSceneId","");
		selectorDialog = new ProgressDialog(this);  
		selectorDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置进度条的形式为圆形转动的进度条  
		selectorDialog.setCancelable(true);// 设置是否可以通过点击Back键取消  
		selectorDialog.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条  
		selectorDialog.setMessage("正在上传，请稍后..."); 
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_choose_pic:
			//Intent intent=new Intent(MedioActivity.this,PicAndVideoActivity.class);
			Intent intent=new Intent(MedioActivity.this,PicAndVideo2Activity.class);
			startActivity(intent);
			finish();
			break;

		case R.id.tv_save:
			finish();
			break;
		case R.id.tv_duomeiti:
			intent=new Intent(MedioActivity.this,Medio2Activity.class);
			startActivity(intent);
			
			break;
		case R.id.rl_return:
			finish();
			break;
		case R.id.tv_photo:

			String state = Environment.getExternalStorageState(); // 判断是否存在sd卡  
	        if (state.equals(Environment.MEDIA_MOUNTED)) { // 直接调用系统的照相机  
	        	File dir = new File(saveDir);  
	            if (!dir.exists()) {  
	                dir.mkdirs(); // 创建文件夹  
	            }
	            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
	            //第二种方法start()
                intent.addCategory(Intent.CATEGORY_DEFAULT);
                fileName = System.currentTimeMillis()+".jpg";
                String filePath = saveDir+"/"+fileName;

                File photoFile = new File(filePath);
                Uri uri = Uri.fromFile(photoFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
              //第二种方法end
	            startActivityForResult(intent, 0);  
	        } else {  
	            Toast.makeText(MedioActivity.this, "请检查是否有SD卡", Toast.LENGTH_LONG)  
	                    .show();  
	        }  
			
		  
			break;
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		 try {  
	            if (requestCode != 0) {  
	                return;  
	            }  
	            super.onActivityResult(requestCode, resultCode, data);  
	            if(requestCode==0){
	            	
		            return;
	            }
	            // 两种方式获得拍摄照片的返回值  
	            Uri uri = data.getData();  
	            if (uri != null) {  
	                photo = BitmapFactory.decodeFile(uri.getPath());  
	            }  
	           // if (photo == null) {  
	                Bundle bundle = data.getExtras();  
	                if (bundle != null) {  
	                    photo = (Bitmap) bundle.get("data");  
	                    SavePicInLocal(photo);// 保存到本地   
	                } else {  
	                    Toast.makeText(MedioActivity.this, "未拍摄照片", Toast.LENGTH_LONG)  
	                            .show();  
	                      
	                }  
	           // }  
	  
	        } catch (Exception e) {  
	  
	        }  
	}
	
	// 保存拍摄的照片到手机的sd卡  
    private void SavePicInLocal(Bitmap bitmap) {  
        FileOutputStream fos = null;  
        BufferedOutputStream bos = null;  
        ByteArrayOutputStream baos = null; // 字节数组输出流  
        try {  
            baos = new ByteArrayOutputStream();  
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);  
            byte[] byteArray = baos.toByteArray();// 字节数组输出流转换成字节数组  
            /*String saveDir = Environment.getExternalStorageDirectory()  
                    + "/hjjc"; */ 
            File dir = new File(saveDir);  
            if (!dir.exists()) {  
                dir.mkdir(); // 创建文件夹  
            }  
            fileName = saveDir + "/" + System.currentTimeMillis() + ".PNG";  
            File file = new File(fileName);  
            file.delete();  
            if (!file.exists()) {  
                file.createNewFile();// 创建文件  
                Log.e("PicDir", file.getPath());  
                /*Toast.makeText(MedioActivity.this, fileName, Toast.LENGTH_LONG)  
                        .show();*/  
            }  
            // 将字节数组写入到刚创建的图片文件中  
            fos = new FileOutputStream(file);  
            bos = new BufferedOutputStream(fos);  
            bos.write(byteArray);  
  
        } catch (Exception e) {  
            e.printStackTrace();  
  
        } finally {  
            if (baos != null) {  
                try {  
                    baos.close();  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
            }  
            if (bos != null) {  
                try {  
                    bos.close();  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
            }  
            if (fos != null) {  
                try {  
                    fos.close();  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
            }  
  
        }  
  
    }  

	public static String getPath(String pathandname){  
        
        int start=pathandname.lastIndexOf("/");  
        if(start!=-1){  
            return pathandname.substring(0,start);    
        }else{  
            return null;  
        }         
    } 

	public static String getFileName(String pathandname){  
        
	      int start=pathandname.lastIndexOf("/");  
      if(start!=-1){  
          return pathandname.substring(start+1);    
      }else{  
          return null;  
      }         
  }


	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		deleteDialog(position);
		
		return true;
	} 
	private void deleteDialog(final int position){
		AlertDialog.Builder builder = new AlertDialog.Builder(MedioActivity.this); 
        builder.setTitle("你确定删除吗");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            	workdao.deleteMediaPath(list.get(position), taskSceneId);
            	data.remove(position);
            	adapter.notifyDataSetChanged();
    			Toast.makeText(MedioActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                             
            }
        });
        builder.create().show();
	}


	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Intent intent = new Intent();       
		intent = FileUtil.getImageFileIntent(list.get(position));
		startActivity( intent );		
	}
}
